"""
线索相关路由
"""
from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user

# 创建蓝图
lead_bp = Blueprint('lead', __name__, url_prefix='/lead')

@lead_bp.route('/list')
@login_required
def lead_list():
    """线索列表"""
    # 获取分页参数
    page = request.args.get('page', 1, type=int)
    per_page = 10
    
    # 获取筛选参数
    search = request.args.get('search', '')
    source = request.args.get('source', '')
    status = request.args.get('status', '')
    manager_id = request.args.get('manager', '')
    priority = request.args.get('priority', '')
    
    # 获取销售线索统计数据
    from app.services import LeadService
    stats = LeadService.get_lead_stats(current_user.id)
    
    # 获取销售线索列表数据
    from app.models.customer import Lead
    from app.models import User
    from app import db
    
    # 构建查询
    query = Lead.query
    
    # 根据用户角色过滤数据
    if current_user.role == 'admin':
        # 管理员可以看到所有线索
        pass
    else:
        # 普通用户只能看到自己负责的线索
        query = query.filter(Lead.assigned_to == current_user.id)
    
    # 应用筛选条件
    if search:
        query = query.filter(Lead.name.contains(search) | Lead.company.contains(search) | Lead.phone.contains(search))
    
    if source:
        query = query.filter(Lead.source == source)
    
    if status:
        query = query.filter(Lead.status == status)
    
    if manager_id:
        query = query.filter(Lead.assigned_to == manager_id)
    
    if priority:
        query = query.filter(Lead.priority == priority)
    
    # 分页
    leads = query.paginate(page=page, per_page=per_page, error_out=False)
    
    # 获取筛选选项
    sources = db.session.query(Lead.source).distinct().all()
    sources = [s[0] for s in sources if s[0]]
    
    statuses = db.session.query(Lead.status).distinct().all()
    statuses = [s[0] for s in statuses if s[0]]
    
    priorities = db.session.query(Lead.priority).distinct().all()
    priorities = [p[0] for p in priorities if p[0]]
    
    managers = User.query.filter(User.role == 'user').all()
    
    return render_template('lead_list.html', 
                          leads=leads.items,
                          stats=stats, 
                          pagination=leads,  # 使用Flask-SQLAlchemy的分页对象
                          page=page,  # 添加当前页码
                          per_page=per_page,  # 添加每页显示数量
                          total_pages=leads.pages,  # 添加总页数
                          search=search,
                          source_filter=source,
                          status_filter=status,
                          manager_filter=manager_id,
                          priority_filter=priority,
                          sources=sources,
                          statuses=statuses,
                          priorities=priorities,
                          managers=managers,
                          current_menu='lead',
                          current_page='lead_list')

@lead_bp.route('/pool')
@login_required
def lead_pool():
    """线索池"""
    # 获取分页参数
    page = request.args.get('page', 1, type=int)
    per_page = 10
    
    # 获取筛选参数
    search = request.args.get('search', '')
    source = request.args.get('source', '')
    priority = request.args.get('priority', '')
    
    # 获取线索池统计数据
    from app.services import LeadService
    stats = LeadService.get_lead_pool_stats(current_user.id)
    
    # 获取线索池列表数据
    from app.models.customer import Lead
    from app.models import User
    from app import db
    
    # 构建查询 - 只查询未分配的线索
    query = Lead.query.filter(Lead.assigned_to == None)
    
    # 根据用户角色过滤数据
    if current_user.role != 'admin':
        # 普通用户只能看到自己部门或区域的未分配线索
        # 这里可以根据实际业务需求进行调整
        pass
    
    # 应用筛选条件
    if search:
        query = query.filter(Lead.name.contains(search) | Lead.company.contains(search) | Lead.phone.contains(search))
    
    if source:
        query = query.filter(Lead.source == source)
    
    if priority:
        query = query.filter(Lead.priority == priority)
    
    # 分页
    leads = query.paginate(page=page, per_page=per_page, error_out=False)
    
    # 获取筛选选项
    sources = db.session.query(Lead.source).distinct().all()
    sources = [s[0] for s in sources if s[0]]
    
    priorities = db.session.query(Lead.priority).distinct().all()
    priorities = [p[0] for p in priorities if p[0]]
    
    # 获取销售部门用户（用于分配线索）
    sales_users = User.query.filter(User.department == '销售部').all()
    
    # 确保stats对象有total属性
    if not hasattr(stats, 'total'):
        stats.total = getattr(stats, 'unassigned', 0)
    
    return render_template('lead_pool.html', 
                          leads=leads.items,  # 传递items而不是整个分页对象
                          stats=stats, 
                          pagination=leads,  # 使用Flask-SQLAlchemy的分页对象
                          page=page,  # 添加当前页码
                          per_page=per_page,  # 添加每页显示数量
                          total_pages=leads.pages,  # 添加总页数
                          search=search,
                          source_filter=source,
                          priority_filter=priority,
                          sources=sources,
                          priorities=priorities,
                          sales_users=sales_users,
                          current_menu='lead',
                          current_page='lead_pool')

@lead_bp.route('/create', methods=['GET', 'POST'])
@login_required
def create_lead():
    """创建线索"""
    from app.models import User
    
    # 获取所有用户，用于负责人选择
    users = User.query.all()
    
    if request.method == 'POST':
        flash('线索创建成功')
        return redirect(url_for('lead.lead_list'))
    return render_template('lead_form.html', users=users, current_menu='lead', current_page='lead_create')

@lead_bp.route('/detail/<int:lead_id>')
@login_required
def lead_detail(lead_id):
    """线索详情"""
    # 获取线索详情
    from app.models.customer import Lead, LeadFollowUp, LeadLog
    from app.models import User
    from app import db
    
    # 获取线索信息
    lead = Lead.query.get_or_404(lead_id)
    
    # 根据用户角色检查权限
    if current_user.role != 'admin' and lead.assigned_to != current_user.id:
        flash('您没有权限查看此线索详情')
        return redirect(url_for('lead.lead_list'))
    
    # 获取跟进记录
    followups = LeadFollowUp.query.filter_by(lead_id=lead_id).order_by(LeadFollowUp.created_at.desc()).all()
    
    # 获取操作记录
    logs = LeadLog.query.filter_by(lead_id=lead_id).order_by(LeadLog.created_at.desc()).all()
    
    return render_template('lead_detail.html', 
                          lead=lead, 
                          followups=followups, 
                          logs=logs,
                          current_menu='lead',
                          current_page='lead_detail')

@lead_bp.route('/pool/detail/<int:lead_id>')
@login_required
def lead_pool_detail(lead_id):
    """线索池详情"""
    # 获取线索池详情
    from app.models.customer import Lead, LeadLog
    from app.models import User
    from app import db
    import datetime
    
    # 获取线索信息
    lead = Lead.query.get_or_404(lead_id)
    
    # 计算在池中的天数
    days_in_pool = (datetime.datetime.now() - lead.created_at).days if lead.created_at else 0
    
    # 获取操作记录
    logs = LeadLog.query.filter_by(lead_id=lead_id).order_by(LeadLog.created_at.desc()).all()
    
    # 获取销售人员列表（部门为销售部的用户）
    sales_users = User.query.filter(User.department == '销售部').all()
    
    return render_template('lead_pool_detail.html', 
                          lead=lead, 
                          days_in_pool=days_in_pool,
                          logs=logs,
                          sales_users=sales_users,
                          current_menu='lead',
                          current_page='lead_pool_detail')

@lead_bp.route('/<int:lead_id>/assign', methods=['POST'])
@login_required
def assign_lead(lead_id):
    """分配线索给销售人员"""
    # 分配线索
    from app.models.customer import Lead, LeadLog
    from app.models import User
    from app import db
    import datetime
    
    # 获取线索信息
    lead = Lead.query.get_or_404(lead_id)
    
    # 检查线索是否已分配
    if lead.assigned_to:
        return {'success': False, 'message': '该线索已被分配'}
    
    # 获取分配的销售人员ID
    assigned_to = request.form.get('assigned_to')
    if not assigned_to:
        return {'success': False, 'message': '请选择销售人员'}
    
    # 获取销售人员信息
    sales_user = User.query.get(assigned_to)
    if not sales_user or sales_user.department != '销售部':
        return {'success': False, 'message': '无效的销售人员'}
    
    # 分配线索
    lead.assigned_to = int(assigned_to)
    lead.assigned_at = datetime.datetime.now()
    
    # 创建操作日志
    log = LeadLog(
        lead_id=lead_id,
        operation_type='分配',
        operation_content=f'线索已分配给销售人员: {sales_user.name}',
        operator_id=current_user.id
    )
    
    db.session.add(log)
    db.session.commit()
    
    return {'success': True, 'message': '线索分配成功'}

@lead_bp.route('/edit/<int:lead_id>', methods=['GET', 'POST'])
@login_required
def lead_edit(lead_id):
    """编辑线索"""
    from app.models import User, customer
    
    # 获取所有用户，用于负责人选择
    users = User.query.all()
    
    # 获取要编辑的线索
    lead = customer.Lead.query.get_or_404(lead_id)
    
    if request.method == 'POST':
        flash('线索更新成功')
        return redirect(url_for('lead.lead_detail', lead_id=lead_id))
    return render_template('lead_form.html', lead=lead, users=users, current_menu='lead', current_page='lead_edit')

@lead_bp.route('/convert/<int:lead_id>', methods=['GET', 'POST'])
@login_required
def lead_convert(lead_id):
    """将线索转化为客户"""
    from app.models.customer import Lead
    from app.models import User
    from app import db
    
    # 获取线索信息
    lead = Lead.query.get_or_404(lead_id)
    
    # 根据用户角色检查权限
    if current_user.role != 'admin' and lead.assigned_to != current_user.id:
        flash('您没有权限转化此线索')
        return redirect(url_for('lead.lead_list'))
    
    if request.method == 'POST':
        # 处理转化逻辑
        # 这里应该将线索转化为客户的逻辑
        flash('线索已成功转化为客户')
        return redirect(url_for('lead.lead_list'))
    
    # 获取用户列表（用于负责人选择）
    users = User.query.filter_by(role='user').all()
    
    return render_template('lead_convert.html', 
                          lead=lead, 
                          users=users,
                          current_menu='lead',
                          current_page='lead_convert')

@lead_bp.route('/followup/create/<int:lead_id>', methods=['GET', 'POST'])
@login_required
def lead_followup_create(lead_id):
    """创建跟进记录"""
    # 创建跟进记录
    from app.models.customer import Lead, LeadFollowUp
    from app import db
    
    # 获取线索信息
    lead = Lead.query.get_or_404(lead_id)
    
    # 根据用户角色检查权限
    if current_user.role != 'admin' and lead.assigned_to != current_user.id:
        flash('您没有权限为此线索添加跟进记录')
        return redirect(url_for('lead.lead_list'))
    
    if request.method == 'POST':
        # 获取表单数据
        method = request.form.get('method')
        content = request.form.get('content')
        result = request.form.get('result')
        next_followup_time = request.form.get('next_followup_time')
        
        # 创建跟进记录
        from app.models import LeadFollowUp
        import datetime
        
        followup = LeadFollowUp(
            lead_id=lead_id,
            manager_id=current_user.id,
            method=method,
            content=content,
            result=result,
            next_followup_time=datetime.datetime.strptime(next_followup_time, '%Y-%m-%dT%H:%M') if next_followup_time else None
        )
        
        db.session.add(followup)
        db.session.commit()
        
        flash('跟进记录添加成功')
        return redirect(url_for('lead.lead_detail', lead_id=lead_id))
    
    return render_template('lead_followup_form.html', lead=lead, current_menu='lead', current_page='lead_followup_create')

@lead_bp.route('/followup/edit/<int:followup_id>', methods=['GET', 'POST'])
@login_required
def lead_followup_edit(followup_id):
    """编辑跟进记录"""
    # 编辑跟进记录
    from app.models.customer import Lead, LeadFollowUp, LeadLog
    from app import db
    
    # 获取跟进记录
    followup = LeadFollowUp.query.get_or_404(followup_id)
    lead = Lead.query.get_or_404(followup.lead_id)
    
    # 根据用户角色检查权限
    if current_user.role != 'admin' and lead.assigned_to != current_user.id and followup.manager_id != current_user.id:
        flash('您没有权限编辑此跟进记录')
        return redirect(url_for('lead.lead_detail', lead_id=lead.id))
    
    if request.method == 'POST':
        # 获取表单数据
        method = request.form.get('method')
        content = request.form.get('content')
        result = request.form.get('result')
        next_followup_time = request.form.get('next_followup_time')
        
        # 更新跟进记录
        import datetime
        
        followup.method = method
        followup.content = content
        followup.result = result
        followup.next_followup_time = datetime.datetime.strptime(next_followup_time, '%Y-%m-%dT%H:%M') if next_followup_time else None
        
        db.session.commit()
        
        flash('跟进记录更新成功')
        return redirect(url_for('lead.lead_detail', lead_id=lead.id))
    
    return render_template('lead_followup_form.html', lead=lead, followup=followup, current_menu='lead', current_page='lead_followup_edit')

@lead_bp.route('/<int:lead_id>/delete', methods=['POST'])
@login_required
def delete_lead(lead_id):
    """删除线索"""
    from app.models.customer import Lead, LeadFollowUp, LeadLog
    from app import db
    
    # 获取线索信息
    lead = Lead.query.get_or_404(lead_id)
    
    # 根据用户角色检查权限
    if current_user.role != 'admin' and lead.assigned_to != current_user.id:
        flash('您没有权限删除此线索')
        return redirect(url_for('lead.lead_list'))
    
    # 删除相关的跟进记录
    LeadFollowUp.query.filter_by(lead_id=lead_id).delete()
    
    # 删除相关的操作日志
    LeadLog.query.filter_by(lead_id=lead_id).delete()
    
    # 删除线索
    db.session.delete(lead)
    db.session.commit()
    
    flash('线索删除成功')
    return redirect(url_for('lead.lead_list'))